using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace FluentBinding.Threading
{
    /// <summary>
    /// Represents helper methods to wait until .NET event (EventHandler signature) occures
    /// </summary>
    /// <example>
    /// EventWaiter waiter = new EventWaiter();
    ///
    /// myObject.MyEvent += waiter.Handler;
    /// try
    /// {
    ///    ... // Some code that should trigger event to occured
    ///
    ///    waiter.Wait();
    /// }
    /// finally
    /// {
    ///    myObject.MyEvent -= waiter.Handler;
    /// }
    /// </example>
    public sealed class EventWaiter
    {
        #region Ctor

        /// <summary>
        /// Creates instance
        /// </summary>
        public EventWaiter()
        {
            _handler = delegate(object sender, EventArgs e)
                           {
                               _event.Set();
                           };
        } 

        #endregion

        #region Public

        /// <summary>
        /// Waits until event occures
        /// </summary>
        public void Wait()
        {
            _event.WaitOne();
        }

        /// <summary>
        /// Waits until event occures
        /// </summary>
        public bool Wait(int millisecondsTimeout)
        {
            return _event.WaitOne(millisecondsTimeout, false);
        }

        private EventHandler _handler;
        /// <summary>
        /// Gets handler that can be used to subscribe for events
        /// </summary>
        public EventHandler Handler
        {
            get { return _handler; }
        } 

        #endregion

        #region Fields

        AutoResetEvent _event = new AutoResetEvent(false); 

        #endregion
    }

}